#include "engine.h"

#define _MODULE_NAME_ "LuaEnvironment"
using std::ifstream;
LuaEnvironment::LuaEnvironment() {
	lang_name = "LUA"; lang_ver = "5.1.3";
	L = lua_open(); if(!L) { E( _MODULE_NAME_ << " init failed.\n") return; }
	luaL_openlibs(L); /* open all libraries */
	isLoadedXml = isLoadedGL = isLoadedNet = 0;
}

LuaEnvironment::LuaEnvironment(int restricted) {
	lang_name = "LUA"; lang_ver = "5.1.3";
	L = lua_open(); if(!L) { E( _MODULE_NAME_ << " init failed.\n") return; }
	if(restricted) { luaopen_base(L); luaopen_table(L); luaopen_string(L); luaopen_math(L); } /* open all libraries except io */
	else luaL_openlibs(L); /* open all libraries */
}
LuaEnvironment::~LuaEnvironment() {
	if(L)  {
		lua_close(L);
		L = NULL;
	}
}

void LuaEnvironment::load_restrictions(const char *filename) {
	ifstream ban_list(filename);
	char ban_name[1024];
	if(!ban_list) return;
	while(!ban_list.eof()) {
		ban_list.getline(ban_name,1024);
		remove_link(ban_name);
	}
}

inline int LuaEnvironment::load_file(const char *path) {
	if(luaL_loadfile(L,path) != 0) { E( _MODULE_NAME_ << " load failed for " << path << endl ) return -1; }
	lua_pcall(L,0,0,0);
	return 1;
}

inline void LuaEnvironment::load_library_net() {
	if(isLoadedNet) return;
	if(SDLNet_Init()==-1) { E("SDLNet:init: " << SDL_GetError()); return ; }
	// TODO Lua Init
	isLoadedNet = 1;
}
